var gamejs = require("gamejs");
var Draw = require("gamejs/draw");
var waveModule = require("js/waves");
var enemyModule = require("js/enemy");
var nightSceneModule = require("js/scenes/nightScene");

/**
 * LoadingNightScene, the scene where create all the enemies
 * in a wave, so the game will not lag.
 */

/**
 * Creates a LoadingNightScene object to load all the enemies.
 * 
 * @param {ScenesDirector} director The ScenesDirector object that directs the game.
 * @param {Match} match The Match object where the enemies will work.
 * @param {number|undefined} level The level of the wave to load, if not defined takes 0.
 * 
 * @constructor
 */
var LoadingNightScene = exports.LoadingNightScene = function(director, match, level) {
	this.director = director;
	this.match = match;
	//level not given -> level = 0
	this.level = level ? level : 0;
	this.isDrawn = false;
	this.createdWave = [];
	this.requiredWave = waveModule.WAVES[this.level];
	this.waveIndex = 0;
	this.waveLength = this.requiredWave.length;
	
	//background image
	this.background = gamejs.image.load(imgPath + "loadingNightBackground.png");
};

/**
 * Updates the scene: creates an enemy at every call, till the wave is completed.
 * Once completed the wave, it sorts the wave by the enemies time of creation
 * and passes it to a NightScene object, that become the active scene.
 * 
 * @param {number} msDuration The time past from the last call, in ms.
 */
LoadingNightScene.prototype.update = function(msDuration) {
	//even if we don't need check the events, we must call
	//this to delete the useless events
	gamejs.event.get();
	
	if(this.waveIndex >= this.waveLength) {
		//all the enemies are created
		//sort for required time of creation
		this.createdWave.sort(function(obj1, obj2) {
			return obj1.time - obj2.time;
		});
		
		//no more need this scene, if we go back from night
		//we want to go to the day scene
		this.director.popScene();
		//go to night
		this.director.pushScene(new nightSceneModule.NightScene(this.director, this.match, this.createdWave));
		return;
	}
	
	//starts only if the background is already drawn
	if(this.isDrawn) {
		//create one enemy
		var requiredEnemy = this.requiredWave[this.waveIndex++];
		var createdEnemy = new requiredEnemy.constructor(this.match, requiredEnemy.from);
		this.createdWave.push({enemy : createdEnemy, time : requiredEnemy.time});
	}
};

/**
 * Draws the scene in the director Surface: a background and a progress bar.
 */
LoadingNightScene.prototype.draw = function() {
	var surface = this.director.getSurface();
	
	//draws the background
	surface.blit(this.background);
	
	//draws the progress bar
	var startPoint = [0, (DISPLAY_HEIGHT * 2) / 3];
	var progress = Math.round((this.waveIndex / this.waveLength) * DISPLAY_WIDTH);
	var endPoint = [progress, (DISPLAY_HEIGHT * 2) / 3];
	Draw.line(surface, "#00FF00", startPoint, endPoint, 5);
	
	this.isDrawn = true;
};